<template>
  <el-card class="box-card">
    <!-- 上部 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-input
          placeholder="请输入内容"
          v-model="params.query"
          clearable
          @clear="getUsers"
          @keyup.enter.native="getUsers"
        >
          <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="isAddUserDialog = true">添加用户</el-button>
      </el-col>
    </el-row>

    <!-- 列表 -->
    <el-table :data="usersList" style="width: 100%" border stripe>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="id" label="编号" width="180"></el-table-column>
      <el-table-column prop="role_name" label="权限名字" width="180"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="手机"></el-table-column>
      <el-table-column prop="create_time" label="时间"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="handleUpdate(scope.row.id)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleDele(scope.row.id)"
          ></el-button>
          <el-tooltip placement="top" effect="dark" content="分配角色" :enterable="false">
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="handleRoles(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.pagenum"
      :page-sizes="[1, 3, 5, 10]"
      :page-size="params.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加对话框 -->
    <el-dialog title="添加用户" :visible.sync="isAddUserDialog" width="50%" @close="handleAddUserClose">
      <!-- 主体 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        label-width="100px"
        class="demo-ruleForm"
        ref="addFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="isUpdateUserDialog"
      width="50%"
      @close="handleUpdateUserClose"
    >
      <!-- 主体 -->
      <el-form
        :model="updateForm"
        :rules="addRules"
        label-width="70px"
        class="demo-ruleForm"
        ref="updateFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updateForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="updateForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isUpdateUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="isShowRolesDialog"
      width="50%"
      @close="setRoleDialogClose"
    >
      <p>当前的用户:{{userInfo.username}}</p>
      <p>当前的角色:{{userInfo.role_name}}</p>
      <p>
        当前的角色:
        <el-select v-model="selected" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  created() {
    this.getUsers()
  },
  data() {
    var checkEamil = (rules, value, callback) => {
      const emailReg = /^[0-9 a-z A-Z]+@[0-9 a-z A-Z]+\.(com||cn)$/
      if (emailReg.test(value)) {
        return callback()
      }
      return callback(new Error('请正确输入邮箱!'))
    }

    var checkMobile = (rules, value, callback) => {
      const mobileReg = /^1[0-9]{10}/
      if (mobileReg.test(value)) {
        return callback()
      }
      return callback(new Error('请正确输入手机号码!'))
    }

    return {
      selected: '',
      rolesList: [],
      userInfo: {},
      isShowRolesDialog: false,
      params: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      usersList: [],
      total: 0,
      isAddUserDialog: false,
      isUpdateUserDialog: false,
      addForm: {
        username: '',
        email: '',
        role_name: '',
        mobile: '',
        password: ''
      },
      updateForm: {
        username: '',
        email: '',
        mobile: ''
      },
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEamil, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
          // { min: 11, max: 11, message: '请输入正确手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    setRoleDialogClose() {
      this.userInfo = {}
      this.selected = ''
    },
    async saveRolesInfo() {
      if (!this.selected) return this.$message.error('请选择要分配的角色!')
      const {
        data: res
      } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selected
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUsers()
      this.isShowRolesDialog = false
    },
    async handleRoles(userInfo) {
      this.userInfo = userInfo

      const { data: res } = await this.$http.get('roles')
      // if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // this.$message.success(res.meta.msg)
      this.rolesList = res.data
      console.log(this.rolesList)

      this.isShowRolesDialog = true
    },
    async getUsers(params) {
      const { data: res } = await this.$http.get('users', {
        params: this.params
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户失败!')
      // console.log(res)
      this.total = res.data.total
      this.usersList = res.data.users
    },
    handleSizeChange(newSize) {
      this.params.pagesize = newSize
      this.getUsers()
    },
    handleCurrentChange(newPage) {
      this.params.pagenum = newPage
      this.getUsers()
    },
    async changeUserState(user) {
      const { data: res } = await this.$http.put(
        `users/${user.id}/state/${user.mg_state}`
      )
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    handleAddUserClose() {
      // console.log("close");
      this.$refs.addFormRef.resetFields()
    },
    handleUpdateUserClose() {
      this.$refs.updateFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(async vali => {
        // console.log(vali);
        if (!vali) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.isAddUserDialog = false
        this.getUsers()
      })
    },
    updateUser() {
      this.$refs.updateFormRef.validate(async vali => {
        if (!vali) return
        const { data: res } = await this.$http.put(
          'users/' + this.updateForm.id,
          this.updateForm
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.isUpdateUserDialog = false
        this.getUsers()
      })
    },
    async handleUpdate(id) {
      // this.updateForm = user
      // console.log(id)
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return
      this.updateForm = res.data
      this.isUpdateUserDialog = true
    },
    async handleDele(id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (confirmRes === 'cancel') return this.$message.error('已取消删除嗷!')
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUsers()
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}

.el-row {
  margin-bottom: 10px;
}

.el-table {
  font-size: 12px;
}

.el-pagination {
  margin: 10px 0;
}
</style>